package com.sdk.cachesdk.service;

import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service("distributedCache")
public class RedissonCacheServiceImpl implements CacheService {

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public void set(String key, Object value) {
        RBucket<Object> bucket = redissonClient.getBucket(key);
        bucket.set(value);
    }

    @Override
    public void set(String key, Object value, long ttl) {
        RBucket<Object> bucket = redissonClient.getBucket(key);
        bucket.set(value, ttl, TimeUnit.SECONDS);
    }

    @Override
    public <T> T get(String key, Class<T> type) {
        RBucket<T> bucket = redissonClient.getBucket(key);
        return bucket.get();
    }

    @Override
    public boolean delete(String key) {
        return redissonClient.getBucket(key).delete();
    }

    @Override
    public boolean hasKey(String key) {
        return redissonClient.getBucket(key).isExists();
    }

    @Override
    public boolean expire(String key, long ttl) {
        return redissonClient.getBucket(key).expire(ttl, TimeUnit.SECONDS);
    }
}
